// src/utils/request.js
import axios from 'axios'
import { Snackbar } from '@varlet/ui'
const service = axios.create({
  baseURL: '/api',
  timeout: 8000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
  withCredentials: true,
})

// 请求缓存对象（防止重复请求）
service.requestCache = {}

// ---------------------- 请求拦截器 ----------------------
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    if (config.uploadFile) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }

    // 防止重复请求
    const requestKey = `${config.method}-${config.url}`
    if (service.requestCache[requestKey]) {
      service.requestCache[requestKey].abort()
      delete service.requestCache[requestKey]
      Snackbar({
        type: 'danger',
        message: '请勿重复请求',
      })
      return Promise.reject(new Error('重复请求'))
    }

    const controller = new AbortController()
    config.signal = controller.signal
    service.requestCache[requestKey] = controller

    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    Snackbar({
      type: 'danger',
      message: '请求超时，请稍后再试',
    })
    return Promise.reject(error)
  },
)

// ---------------------- 响应拦截器 ----------------------
service.interceptors.response.use(
  (response) => {
    const res = response.data
    console.log('接口响应:', res)

    // 根据后台返回格式处理响应
    if (res.code !== 200) {
      Snackbar({
        type: 'danger',
        message: res.message || '操作失败',
      })

      if (res.code === 401) {
        localStorage.removeItem('token')
        setTimeout(() => {
          window.location.href = '/login'
        }, 1500)
      }

      return Promise.reject(new Error(res.message || '接口请求失败'))
    }

    // 操作成功时可以显示成功提示（可选）
    if (res.message && res.message !== '操作成功') {
      Snackbar({
        type: 'success',
        message: res.message,
      })
    }

    return res.data
  },
  (error) => {
    console.error('响应拦截器错误:', error)

    let errorMsg = '网络异常，请稍后重试'
    if (error.response) {
      switch (error.response.status) {
        case 404:
          errorMsg = '接口不存在'
          break
        case 500:
          errorMsg = '服务器内部错误'
          break
        case 403:
          errorMsg = '无访问权限'
          break
        case 401:
          errorMsg = '登录状态已过期，请重新登录'
          break
      }
    } else if (error.request) {
      errorMsg = '网络连接失败，请检查网络'
    } else if (error.code === 'ECONNABORTED') {
      errorMsg = '请求超时，请稍后再试'
    }

    Snackbar({
      type: 'danger',
      message: errorMsg,
    })
    return Promise.reject(error)
  },
)

// ---------------------- 核心请求函数 ----------------------
const coreRequest = (method, url, data = {}, config = {}) => {
  const isGet = method.toLowerCase() === 'get'
  return service({
    url,
    method,
    ...(isGet ? { params: data } : { data }),
    ...config,
  })
}

// ---------------------- 创建request对象 ----------------------
export const request = {
  // 通用请求方法
  request: (options) =>
    coreRequest(options.method || 'get', options.url, options.data || {}, options.config || {}),

  // GET请求
  get: (url, params = {}, config = {}) => coreRequest('get', url, params, config),

  // POST请求
  post: (url, data = {}, config = {}) => coreRequest('post', url, data, config),

  // PUT请求
  put: (url, data = {}, config = {}) => coreRequest('put', url, data, config),

  // DELETE请求
  delete: (url, params = {}, config = {}) => coreRequest('delete', url, params, config),

  // 文件上传
  upload: (url, formData, config = {}) =>
    coreRequest('post', url, formData, { ...config, uploadFile: true }),
}
